﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Seesmic.Sdp.Extensibility;
using System.Threading;
using Seesmic.Sdp.Utils;
using PTiRouZ.Net.SilverLight.Api.HelloTipi;
using PTiRouZ.Net.SilverLight.Api;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Globalization;

namespace Seesmic.HelloTipi
{
    public class HelloTipiFriendsTimeLineItemsProvider : ITimelineItemsProvider 
    {

        #region Fields

        private Timer _Timer;

        private int messageId = 0;

        private HelloTipiAccount _account;

        public apitxt api;

        #endregion Fields

        #region Properties

        public HelloTipiTimeLine Timeline
        {
            get;
            private set;
        }

        #endregion Properties

        #region ITimelineItemsProvider Members

        public event EventHandler<TimelineItemEventArgs> ItemAdded;

        public event EventHandler<TimelineItemEventArgs> ItemRemoved;

        #region Constructors

        public HelloTipiFriendsTimeLineItemsProvider(HelloTipiAccount Account)
        {
            _account = Account;

            this.Timeline = new HelloTipiTimeLine();

            this.api = new apitxt(Account.Username, Account.Password, "Seesmic Desktop 2");

            this.api.APICallError += delegate(object sender, ApiErrorEventArgs e)
            {
                HelloTipiPlugin.ShowDialogNotification("Erreur de l'api", "{0}", DialogNotificationButtons.OK, e.Message);
            };

            this.api.FriendsTimelineCompleted += new FriendsTimelineEventHandler(api_FriendsTimelineCompleted);
            
            _Timer = new Timer(OnTimerTick, null, 0, 10000);
        }

        #endregion Constructors
        
        public void OnItemProcessed(ProcessingResult result)
        {
            if (result.Blocked == false && result.Error == null)
            {
                Timeline.Add(result.TimelineItemContainer);
            }
        }

        private void OnItemAdded(TimelineItemEventArgs e)
        {
            var handler = ItemAdded;

            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void OnItemRemoved(TimelineItemEventArgs e)
        {
            //HelloTipiPlugin.LogInfo("Friends OnItemRemoved " + e.TimelineItemContainer.TimelineItem.Id);

            Timeline.Remove(e.TimelineItemContainer);
            
            var handler = ItemRemoved;

            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void OnTimerTick(object state)
        {
            //HelloTipiPlugin.LogInfo("OnTimerTick ("+messageId+") : " + DateTime.Now.ToLongTimeString());

            if (messageId > 0)
                this.api.FriendsTimeline(null, messageId);
            else
                this.api.FriendsTimeline(null, null, 30);
        }

        void api_FriendsTimelineCompleted(object sender, FriendsTimelineEventArgs e)
        {
            
            e.result.ForEach(delegate(friends_timeline friendsTimeline)
            {
                
                HelloTipiTimeLineItem Item = new HelloTipiTimeLineItem
                {
                    Id = friendsTimeline.id.ToString(),
                    Text = friendsTimeline.text,
                    DateTime = DateTime.ParseExact(friendsTimeline.created_at, "ddd MMM d H:mm:ss zzz yyyy", CultureInfo.InvariantCulture), //D M j H:i:s O Y = ddd MMM d H:mm:ss zzz yyyy
                    Site = HelloTipiPlugin.getSite(friendsTimeline.site.name),
                    User = friendsTimeline.user,
                    Source = new Uri(friendsTimeline.source),
                    Account = this._account,
                    isFamilyTimeline = false,
                    isPrivateTimeline = false
                };

                TimelineItemContainer container = new TimelineItemContainer(Item);
                container.AddAction(new MentionAction(Item.Username));
                container.AddAction(new PrivateAction(Item.Username));
                container.AddAction(new DeleteAction(int.Parse(Item.Id), OnItemRemoved));
                container.AddQuickAction(new MentionAction(Item.Username));
                container.AddQuickAction(new PrivateAction(Item.Username));

                if (Item.UsernamewithoutFamily == Item.Account.Username)
                    container.HighlightColor = ItemHighlightColors.Sent;

                else if (Item.Text.ToLower().Contains(Item.Account.Username.ToLower()))
                    container.HighlightColor = ItemHighlightColors.Reply;
                
                else if (Item.Text.StartsWith("Inscription de"))                    
                    container.HighlightColor = Color.FromArgb(255, 255, 106, 0); 

                SynchronizationHelper.Post(OnItemAdded, new TimelineItemEventArgs(container));

                if (messageId < friendsTimeline.id)
                messageId = friendsTimeline.id;
            });
        }

        #endregion
    }
}
